package com.service.atf.core;

import com.service.atf.exception.TFException;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * User: luotao
 * Date: 12-6-25
 * Time: 13:40
 */
public class TFAccessor {
    private static final int LEN_HEAD=4;

    RandomAccessFile out;

    FileChannel bodyChannel;

    MappedByteBuffer bodyBuffer;

    FileChannel headChannel;

    MappedByteBuffer headBuffer;

    public TFAccessor(String path, int max) {
        try {
            out = new RandomAccessFile(path, "rw");
            bodyChannel = out.getChannel();
            bodyBuffer = bodyChannel.map(FileChannel.MapMode.READ_WRITE, 0, 1024*1024);
        } catch (Exception e) {
            e.printStackTrace();
            throw new TFException(e.toString());
        }
    }

    public void write(ByteBuffer input) {
        bodyBuffer.put(input);
    }

    public byte[] read(int position) {
        try {
            ByteBuffer buffer = ByteBuffer.allocate(position);
            bodyChannel.read(buffer);
            return buffer.array();
        } catch (IOException e) {
            e.printStackTrace();
            throw new TFException(e.toString());
        }
    }

    public void close() {
        try {
            bodyChannel.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
            throw new TFException(e.toString());
        }
    }

    public static void main(String[] args) throws Exception {
        String path = "e:\\data\\TF\\111.txt";
        TFAccessor tfAccessor = new TFAccessor(path,10000);
        ByteBuffer buffer = ByteBuffer.allocate(100);
        buffer.put("hello".getBytes());
        tfAccessor.write(buffer);
    }
}
